package net.lab1024.sa.admin.module.app.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.module.app.req.AppOrderDetailReq;
import net.lab1024.sa.admin.module.app.req.AppOrderListReq;
import net.lab1024.sa.admin.module.app.rsp.AppOrderDetailRsp;
import net.lab1024.sa.admin.module.app.rsp.AppOrderListRsp;
import net.lab1024.sa.admin.module.business.bjd.domain.entity.DollEntity;
import net.lab1024.sa.admin.module.business.bjd.domain.entity.OrderEntity;
import net.lab1024.sa.admin.module.business.bjd.domain.entity.UserDollBindEntity;
import net.lab1024.sa.admin.module.business.bjd.domain.form.OrderQueryForm;
import net.lab1024.sa.admin.module.business.bjd.domain.vo.OrderVo;
import net.lab1024.sa.admin.module.business.bjd.mapper.OrderMapper;
import net.lab1024.sa.base.common.domain.RequestUser;
import net.lab1024.sa.base.common.exception.BusinessException;
import net.lab1024.sa.base.common.util.SmartRequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author guolong.zhang
 * @date 2025/02/10 09:10
 **/
@Service
@Slf4j
public class AppOrderService {

    @Autowired
    private OrderMapper orderMapper;
    public List<AppOrderListRsp> orderList(AppOrderListReq req) {
        List<AppOrderListRsp> list = new ArrayList<>();
        Page page = new Page<>(1,10);
        OrderQueryForm queryForm = BeanUtil.toBean(req, OrderQueryForm.class);
        List<OrderVo> orderVos = orderMapper.pageList(page, queryForm);
        for (OrderVo vo : orderVos) {
            String dollNo = vo.getDollNo();
            DollEntity doll = Db.lambdaQuery(DollEntity.class)
                    .eq(DollEntity::getDollNo, dollNo)
                    .last("limit 1")
                    .one();
            if(doll == null){
                throw new BusinessException("娃娃不存在");
            }
            RequestUser requestUser = SmartRequestUtil.getRequestUser();
            Long count = Db.lambdaQuery(UserDollBindEntity.class)
                    .eq(UserDollBindEntity::getOrderNo, vo.getOrderNo())
                    .eq(UserDollBindEntity::getUserId, requestUser.getUserId())
                    .count();
            AppOrderListRsp rsp = BeanUtil.toBean(vo, AppOrderListRsp.class);
            if(count> 0){
                rsp.setIsMindBind(Boolean.TRUE);
            }
            rsp.setImageUrl(doll.getImgUrl());
            list.add(rsp);
        }
        return list;
    }

}
